<!DOCTYPE html>
<html lang="zh">

	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<meta http-equiv="X-UA-Compatible" content="ie=edge" />
		<title>Document</title>
		<style type="text/css">
			.btn {
				display: inline-block;
				height: 20px;
				border: 1px solid dodgerblue;
				background-color: lightblue;
				padding: 4px 10px;
				text-align: center;
				text-decoration: none;
				color: white;
				cursor: pointer;
			}
			
			.btn:hover {
				opacity: 0.7;
				text-decoration: underline;
			}
		</style>
		<script type="text/javascript">
			function downloadFile(aLink, fileName, content) {
				aLink.download = fileName;
				aLink.href = "data:text/plain," + content;
			}

			function downloadFileX2(fileName, content) {
				var aLink = document.createElement('a');
				var blob = new Blob([content]);
				var evt = document.createEvent("HTMLEvents");
				evt.initEvent("click", false, false); //initEvent 不加后两个参数在FF下会报错, 感谢 Barret Lee 的反馈
				aLink.download = fileName;
				aLink.href = URL.createObjectURL(blob);
				aLink.dispatchEvent(evt);
			}

			function downloadFile1(ctx) {
				var c = document.querySelector('#content').innerText;
				downloadFile(ctx, 'no-server-file-a.txt', c);
			}

			function downloadFile2() {
				var c = document.querySelector('#content').innerText;
				downloadFileX2('no-server-file-a.txt', c);
			}
		</script>
	</head>

	<body>
		<a href="http://www.alloyteam.com/2014/01/use-js-file-download/comment-page-1/">http://www.alloyteam.com/2014/01/use-js-file-download/comment-page-1/</a>
		<div id="">
			<p>鼠标移到下面文件后，右键然后选择<b>链接另存为</b></p>
			<a class="btn" href="../data/file-a.js">file-a.js</a>
		</div>
		<div id="">
			<p>点击按钮即可保存</b>
			</p>
			<a class="btn" href="../data/file-a.js" download>file-a.js</a>
		</div>
		<div id="">
			<p>点击按钮即可保存</b>
			</p>
			<a class="btn" href="../data/file-a.js" download="the-source-name-is-file-a.js">the-source-name-is-file-a.js</a>
		</div>
		<div id="">
			<p>点击按钮即可保存如下文本</b>
				<p id="content" style="display: inline-block;border-radius: 5px;width: 300px;height: 60px;text-align:center;line-height: 60px;background-color: #FFA;">弱水三千，只取一瓢饮</p>
			</p>
			<a class="btn" onclick="downloadFile1(this)">保存上面文本为文件并下载</a>
			<a class="btn" onclick="downloadFile2()">保存上面文本为文件并下载 <span style="color: red;">(已失效)</span></a>
		</div>
	</body>

</html>